/* api */
import { getConnectorList, deleteConnector } from '@src/modules/connector/api'
import * as triggerApi from '@src/modules/connector/api/trigger';
/* hooks */
import { useLoading } from '@hooks/useLoading'
/* model */
import { ConnectorModuleErrorMessageEnum } from '@src/modules/connector/model'
import { CreateConnectorFieldNameEnum } from '@src/modules/connector/view/list/model'
import MsgModel from '@model/MsgModel'
/* util */
import { message, confirm } from '@src/util/message'
import { isFalse, isFalsy } from '@src/util/type'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'
/* vue */
import { computed, Ref, ref } from 'vue'
import { ConnectorSettingCardItem, TriggerSettingCardItem } from '@src/modules/connector/types'
import { t } from '@src/locales'


function useConnectorList(params:any) {
  
  const { loading: fetchConnectorListLoading, connectorList, fetchConnectorList } = useFetchConnectorList(params)
  const { loading: fetchDeleteConnectorListLoading, fetchDeleteConnector } = useFetchDeleteConnector()
  
  const initialize = () => {
    fetchConnectorList()
  }
  
  /** 
   * @description 删除触发器
   * @param {TriggerSettingCardItem} item 删除的触发器项
  */
  const onDeleteConnectorHandler = async (item: TriggerSettingCardItem) => {
    
    const confirmed = await confirm.warning(t('common.connector.trigger.deleteTips'))
    
    if (isFalsy(confirmed)) {
      return
    }

    
    fetchDeleteConnector(item.id)
      .then((result:boolean) => {
        if (result) {
          fetchConnectorList()
        }
        
      })
    
  }
  
  const onEditConnectorHandler = (value:TriggerSettingCardItem) => {
    // TODO: 跳转到编辑页面
    let searchParams = {}
    try {
      // 从API设置下面触发器列表编辑触发器
      searchParams = Object.fromEntries(new URLSearchParams(location.search).entries()) || {}
    } catch (error) {
      console.warn(error)
    }
    let fromId = window.frameElement?.getAttribute('id');
    if(searchParams.from === 'api' || searchParams.from === 'auth') {
      // 从系统集成中心下的触发器列表或者第三方应用设置下面的触发器列表过来   
      fromId = window?.parent?.frameElement?.getAttribute('id')
    }
    let params = `id=${value.id}&sync=${value.sync}`
    if(searchParams.from) params += `&from=${searchParams.from}`
    openAccurateTab({
      type: PageRoutesTypeEnum.PageConnectorSetting,
      titleKey: value.triggerNo,
      key:value.id,
      params,
      fromId
    })
  }
  
  return {
    
    connectorList,
    fetchConnectorListLoading,
    
    initialize,
    onDeleteConnectorHandler,
    onEditConnectorHandler
  }
}

/**
 * @description 获取触发器列表
 */
function useFetchConnectorList(params:any) {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const connectorList = ref([])

  
  const fetchConnectorList = () => {
    
    setLoading()
    
    return (
      triggerApi.getTriggerInfoList(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const data = result?.data?.list || []
          connectorList.value = data
          
        } else {
          message.error(result?.message || '')
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    connectorList,
    fetchConnectorList
  }
}

/**
 * @description 删除触发器
 */
function useFetchDeleteConnector() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const fetchDeleteConnector = (id: string) => {
    
    setLoading()
    
    return (
      triggerApi.deleteTrigger(id).then((result:any) => {
        
        if (MsgModel.isSuccess(result)) {
          message.success(t('common.base.deleteSuccess'))
          return result
          
        } else {
          
          message.error(result?.message || ConnectorModuleErrorMessageEnum.DeleteConnector)
          
          return false
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    fetchDeleteConnector
  }
}

function useConnectListDialog() {
  
  const isCreateConnector = ref(false)
  const isEditConnector = computed(() => isFalse(isCreateConnector))
  
  const formValue: Ref<Record<CreateConnectorFieldNameEnum, string>> = ref({
    id:'',
    name: '',
    description: ''
  })
  
  const dialogTitle = computed(() => {
    return isCreateConnector.value ? t('common.base.createModule', {data1: t('common.connector.title.trigger')}) : t('common.base.editModule', {module: t('common.connector.title.trigger')})
  })
  
  const resetFormValue = () => {
    formValue.value = {
      id:'',
      name: '',
      description: ''
    }
  }
  
  const setFormValue = (item: TriggerSettingCardItem) => {
    formValue.value = {
      id: item.id || '',
      name: item.triggerName,
      description: item.triggerDesc
    }
  }
  
  const setIsCreateConnector = (value: boolean = true) => {
    isCreateConnector.value = value
  }
  
  return {
    isCreateConnector,
    isEditConnector,
    formValue,
    dialogTitle,
    resetFormValue,
    setFormValue,
    setIsCreateConnector
  }
}

export {
  useConnectorList,
  useFetchConnectorList,
  useConnectListDialog
}
